$(document).ready( function() {
  //load orbited libraries:
  if(!window.console) {
    window.console = function(){}
    window.console.log = function(data) {}
    window.console.error = function(data) {}
  }
  $.getScript("/orbited/JSON.js");
  $.getScript("/orbited/Orbited.js", 
              function() { 
                TCPSocket = Orbited.TCPSocket;
                $.getScript("/orbited/protocols/stomp/stomp.js", initiateOrbit);
              });   
    
  
  $('legend.collapsed').each(function() { $(this).siblings().toggle() });
  $('legend').each(function() {
                      $(this).html('<a href="javascript:(function(){})()"> ' + $(this).text() + '</a>');
                   });    
  $('legend a').click(function() {$(this).parent().siblings().toggle();});  
  $('.submitForm').bind('click', function(event) { event.preventDefault(); 
                                                   event.stopPropagation();  
                                                   submitForm($(this).parent()); 
                                                   return false;});                                                   
  $('.submitForm').parent().attr('onsubmit', 'submitForm($(this)); return false');
    
});

var last_msg = null;
var stomp = null;
var TCPSocket = null;
stopStomp = function() {
  stomp.disconnect();
}

initiateOrbit = function() {    
  stomp = new STOMPClient();    
  stomp.onopen = function() {
      console.log("Transport openned");
  };
  stomp.onclose = function(code) {
      console.log("Transport closed (code: " + code + ")");
      stomp.closed = true;
  };
  stomp.onerror = function(error) {
      console.log("onerror: " + error);
  };
  stomp.onerrorframe = function(frame) {
      console.log("onerrorframe: " + frame.body);
  };
  stomp.onconnectedframe = function() {
      console.log("Connected as user ");
      stomp.closed = false;
      stomp.subscribe('/client/' + stomp.id);
  };
  stomp.onmessageframe = function(frame) {    
      msg = JSON.parse(frame.body);
      if(msg.paused) {        
        $('.pause').hide();        
        $('.resume').show();
      } else {
        $('.pause').show();        
        $('.resume').hide();        
      }                                    
      
      if(stomp_msg_callback == undefined) {
        console.error('please provide stomp_msg_callback implementation');
      } else {
        stomp_msg_callback(msg);
      }                 
      last_msg = msg;
  };
  stomp.sendmsg = function(method, args) {
      this.send(JSON.stringify({method:method,args:args, id:this.id}),'/server'); 
  }  
  stomp.id = getQueryVariable('id');  
  findPortAndConnect = function() {$.get('/stomp-port', function(stompPort) { if(stompPort) stomp.connect('localhost', stompPort, '', '');})}   
  checkConnection = function() {
    if(stomp.closed) {
      if($('#disconnected').length == 0)
        $('body').prepend('<div id=disconnected> Disconnected, check if program is running, then, refresh</div>');        
    } else if($('#disconnected').length > 0) {
        $('#disconnected').remove();
    }
  }
  findPortAndConnect();
  setInterval(checkConnection, 10000);
};



set_table_row = function(id, ind, row) {
  //console.log('set_table_row'); 
  num_cols = $('#' + id + ' tr:first th').length;
  //console.log('num_cols = ' + num_cols);
  while($('#' + id + ' tr').length < ind + 2) {
    //console.log('appending a row');
    $('#' + id + ' tr:last').after('<tr>' + new Array(num_cols+ 1).join('<td></td>') + '</tr>');
    //console.log("current number of rows = " + $('#' + id + ' tr').length);
  }
  for(i = 1; i <= num_cols; ++i) {
    el = $('#'+id+' tr:nth-child(' + (ind+2) + ') td:nth-child(' + i  + ')');
    if(el.text() != row[i-1])
      el.text(row[i-1]);
  } 
}

refresh_table = function(id, rows) { 
  num_rows = rows.length;
  while( $('#' + id + ' tr').length > num_rows + 1) {
    $('#' + id + ' tr:last').remove();
  }
  $(rows).each(function(i, row) {
                 set_table_row(id, i, row);
               });
}

create_table = function(parentid, rows) {
  p = $('#' + parentid )
  if(rows.length == 0) {
    p.html('no rows');
    return;
  }
  num_cols = rows[0].length; 
  tableid = 'table-' + parentid
  p.html('<table id="' + tableid+'"></table>' );
  t = $('#' + tableid);
  header = '<tr>'
  for(i = 0; i < num_cols; ++i)
      header += '<th>COL' + i + '</th>'
  header += '</tr>'
  t.html(header)
  refresh_table(tableid, rows)
}

onunload = function() { stomp.disconnect(); }
  

submitForm = function(el) {  
  arr = el.serializeArray();
  data = {};
  method = '';
  for(i in arr) {    
    obj = arr[i];
    if(obj.name == 'name' && !obj.value) {
      alert('specify peer name');      
      return false;
    }
    if(obj.name == 'method') {
      method = obj.value;
    } else {
      data[obj.name] = obj.value;
    }
  }
  stomp.sendmsg(method,data);
  return false;
}


getQueryVariable = function(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return 'first';  
}
